<template>
	<notice :notice.sync="notice"></notice>
	<header-class action="student" :class-info.sync="classInfo"></header-class>

	<div class="container">
	    <div class="loading-class" v-if="indexLoading">
			<i class="fa fa-spinner fa-spin fa-3x"></i>
		</div>
	    <div class="row stus-title">
	        <div class="col-md-2">
	            <a :href="'/export/exportClassStu?cad='+claId" class="btn btn-info exportClassStudent">导出学生名单</a>
	        </div>
	        <div class="col-md-4 info">
	            学生通过此邀请码加入课堂 : {{classInfo.cla_code}}
	        </div>
	        <div class="col-md-3 class-number info">
	            班级人数 : <span>{{classInfo.cla_stu_num}}</span>
	        </div>
	        <div class="col-md-2">
	            <div class="input-group input-group-sm">
	                <span class="input-group-btn">
	                    <button class="btn btn-default" type="button" @click="getStus(true)" :disabled="indexLoading">
	                        <span class="glyphicon glyphicon-search"></span>
	                    </button>
	                </span>
	                <input type="text" class="form-control" placeholder="学号 、姓名" 
	                	v-model="searchText" 
	                	debounce='500'
	                	@keyup.enter="getStus(true)">
	            </div>
	        </div>
	    </div>
	    <div class="row">
	        <div class="col-md-2">
	            <div class="list-group">
	                <a style="text-align: center;" class="list-group-item">功能</a>
	                <a href class="list-group-item pointer" data-toggle="modal" data-target="#apply-modal">
                        查看申请表
                        <span class="badge" id="applyNum">{{applyNumber}}</span>
	                </a>
	                <a href class="list-group-item" data-toggle="modal" data-target="#add-stu">导入学生</a>
	                <a href="javascript:;" class="list-group-item list-group-item-danger" title="选择学生后才启用"
	                	:class="{'disabled': !isSelectOne}"
	                	@click="beforeDel(false, $event)">删除
	                </a>
	            </div>
	        </div>
	        <div class="col-md-9" v-if="!indexLoading">
                <table class="table table-hover stuInfo-table" v-if="students.length>0">
                    <tr class="table-header">
                        <th><input type="checkbox" v-model="isSelectAll"/><a href="jvascript:;" @click="toggle('students')"> 反选</a> </th>
                        <th>学号</th>
                        <th>姓名</th>
                        <th>邮箱</th>
                        <th>操作</th>
                    </tr>
                    <tr v-for="stu in students" transition="fade" @click="stu.checked=!stu.checked">
                        <td><input type="checkbox" v-model="stu.checked"/></td>
                        <td>{{stu.stu_number}}</td>
                        <td>{{stu.stu_name}}</td>
                        <td>{{stu.stu_email}}</td>
                        <td class="edit-stu">
                            <span class="glyphicon glyphicon-option-horizontal"></span>
                            <span class="glyphicon glyphicon-remove" title="移除学生" @click="beforeDel(true, $event, $index)"></span>
                        </td>
                    </tr>
                </table>
                <div class="no_stu" v-else>
                    <p v-if="!searchText">本班级暂时没有学生加入</p>
                    <p v-else>查找不到相关学生</p>
                    <p>让学生使用以下代码加入课堂 ：{{classInfo.cla_code}}</p>
                </div>
            </div>
	    </div>
	    <div class="row" v-if="!loading">
            <div class="col-md-3 col-md-offset-5">
                <pagenation v-if="pageInfo.page>1"
                			:page-info="pageInfo"
                			@update-np="updatePage">
                </pagenation>
            </div>
	    </div>
	</div>
	<modal type="modal-sm" id="del-stus">
		<h4 slot="header" class="modal-title text-danger">{{delInfo.title}}</h4>
		<p slot="body">是否删除学生 <span class="text-info">{{delInfo.content}}</span></p>
		<button slot="footer" type="button" class="btn btn-danger" @click="delStus">删除</button>
	</modal>
	<modal id="add-stu">
		<h4 slot="header" class="modal-title">导入学生</h4>
		<template slot="body">
			<div class="row">
				<div class="col-md-6">
	                <select class="form-control input-sm" :disabled="importLoading" v-model="selectedClass" @change="getOtherStus(false)">
	                    <option class="selected" value="-1">请选择导入班级</option>
	                    <option v-for="cla in classes" :value="cla.cla_id">{{cla.cla_name}}</option>
	                </select>
	            </div>
	            <div class="col-md-6">
	                <div class="input-group input-group-sm">
	                    <input type="text" class="form-control" placeholder="学号" v-model="imptSearchText">
	                    <span class="input-group-btn">
	                        <button class="btn btn-default" type="button" @click="getOtherStus(true)" :disabled="importLoading">
	                            <span class="glyphicon glyphicon-search"></span>
	                        </button>
	                    </span>
	                </div>
	            </div>
	        </div>
	        <br/>
	        <div class="row modal-table">
	            <table class="table table-hover">
	                <tr class="table-header">
	                    <th><input type="checkbox" v-model="isImportSelectAll"/> </th>
	                    <th>学生学号</th>
	                    <th>学生姓名</th>
	                </tr>
	                <tr v-for="stu in otherStus" track-by="stu_id" transition="fade" @click="stu.checked=!stu.checked">
	                	<td><input type="checkbox" v-model="stu.checked"></td>
	                	<td>{{stu.stu_number}}</td>
	                	<td>{{stu.stu_name}}</td>
	                </tr>
	            </table>
	        </div>
        </template>
		<button slot="footer" type="button" class="btn btn-primary" @click="addStus" :disabled="!isImportSelectOne||importLoading">提交</button>
	</modal>
	<modal id="apply-modal">
		<h4 slot="header" class="modal-title">学生申请表</h4>
		<template slot="body">
	        <div class="row modal-table">
	            <table class="table table-hover">
	                <tr class="table-header">
	                    <th><input type="checkbox" v-model="isApplySelectAll"/> </th>
	                    <th>学生学号</th>
	                    <th>学生姓名</th>
	                </tr>
	                <tr v-for="stu in applyStus" track-by="$index" transition="fade" @click="stu.checked=!stu.checked">
	                	<td><input type="checkbox" v-model="stu.checked"></td>
	                	<td>{{stu.stu_number}}</td>
	                	<td>{{stu.stu_name}}</td>
	                </tr>
	            </table>
	        </div>
        </template>
        <template slot="footer">
			<button slot="footer" type="button" class="btn btn-danger" @click="delApply" :disabled="!isApplySelectOne||applyLoading">删除</button>
			<button slot="footer" type="button" class="btn btn-primary" @click="allowApply" :disabled="!isApplySelectOne||applyLoading">通过</button>
        </template>
	</modal>
</template>

<script>
	import HeaderClass from '../../Component/HeaderClass/HeaderClass';
	import Pagenation from '../../Component/Pagenation/Pagenation';
	import Modal from '../../Component/Modal/Modal';
	import Notice from '../../Component/Notice/Notice';

	export default {
		created: function() {
			this.claId = location.search.slice(1).split('=')[1];
			this.getStus();
			this.getApplyStus();
		},
		data() {
			return {
				claId: -1,
				notice: {type: 0, msg: ""},
				classInfo: {},
				students: [],
				otherStus: [],
				applyStus: [],
				classes: [],
				delInfo: {isSingle: false, title: "", content: "", delIndex: -1},
				selectedClass: -1,
				importLoading: false,
				searchText: "",
				imptSearchText: "",
				indexLoading: false,
				importLoading: false,
				applyLoading: false,
				applyNumber: 0,
				pageInfo: {}
			}
		},
		computed: {
			isSelectAll: {
				get: function() {
					return this.students.length>0&&this.students.every(function(el) {
						return el.checked;
					});
				},
				set: function() {
					var isSelectAll = this.isSelectAll;
					console.log(isSelectAll)
					this.students.forEach(function(el) {
						el.checked = !isSelectAll;
					})
				}
			},
			isSelectOne: function() {
				return this.students.some(function(el) {
					return el.checked;
				});
			},
			isImportSelectAll: {
				get: function() {
					return this.otherStus.length>0&&this.otherStus.every(function(el) {
						return el.checked;
					});
				},
				set: function() {
					var isImportSelectAll = this.isImportSelectAll;
					this.otherStus.forEach(function(el) {
						el.checked = !isImportSelectAll;
					})
				}
			},
			isImportSelectOne: function() {
				return this.otherStus.length>0&&this.otherStus.some(function(el) {
					return el.checked;
				});
			},
			isApplySelectAll: {
				get: function() {
					return this.applyStus.length>0&&this.applyStus.every(function(el) {
						return el.checked;
					});
				},
				set: function() {
					var isApplySelectAll = this.isApplySelectAll;
					this.applyStus.forEach(function(el) {
						el.checked = !isApplySelectAll;
					})
				}
			},
			isApplySelectOne: function() {
				return this.applyStus.some(function(el) {
					return el.checked;
				});
			},
		},
		components: {
			HeaderClass,
			Pagenation,
			Modal,
			Notice
		},
		methods: {
			getStus: function(bySearch, np) {
				if (this.indexLoading) return;
				if (bySearch) bySearch = !!(this.searchText);

				if (bySearch) {
					this.indexLoading = true;
					this.$http.post('/Student/search', {cla_id: this.claId, keyword: this.searchText}).then(function(resp) {
			        	this.indexLoading = false;
			            if (resp.data.status === 1) {
			        		resp.data.data.forEach((el) => {
			        			el.checked = false;
			        		})
			        		this.students = resp.data.data;
			        	}
				    }, function(resp) {
				        // error callback
				        this.indexLoading = false;
				        this.notice = {type: 0, msg: resp.statusText};
				    })
				} else {
					this.indexLoading = true;
					this.$http.post('/classStudent/classStuInfo', {cla_id: this.claId, np: np||1}).then(function(resp) {
			        	this.indexLoading = false;
			        	if (resp.data.status === 1 && resp.data.data.student) {
			        		resp.data.data.student.forEach((el) => {
			        			el.checked = false;
			        		})
			        		this.students = resp.data.data.student;
			        		this.pageInfo = resp.data.data.pageInfo;
			        	}
				    }, function(resp) {
				        // error callback
				        this.indexLoading = false;
				        this.notice = {type: 0, msg: resp.statusText};
				    })
				}
				
			},
			updatePage: function(np) {
				if (np == this.pageInfo.np)
					return
				this.getStus(false, np);
			},
			getApplyStus: function () {
				this.$http.post('/classStudent/getApplyStu', {cla_id: this.claId}).then(function(resp) {
		        	if (resp.data.status === 1) {
		        		if (resp.data.data) {
		        			resp.data.data.forEach((el) => {
		        				el.checked = false;
		        			})
		        			this.applyStus = resp.data.data;
		        			this.applyNumber = this.applyStus.length;
		        		}
		        		
		        	}
			    }, function(resp) {
			        // error callback
			    })
			},
			getAllClasses: function() {
				this.$http.post('/class/otherClass', {cla_id: this.claId, cou_id: 1}).then(function(resp) {
		        	if (resp.data.status === 1) {
		        		if (resp.data.data) {
		        			this.classes = resp.data.data;
		        		}
		        	}
			    }, function(resp) {
			        // error callback
			    })
			},
			getOtherStus: function(isSingle) {
				if (isSingle) {
					this.selectedClass = -1;
					if (!this.imptSearchText) return;
				} else {
					this.imptSearchText = "";
					if (this.selectedClass == -1) return;
				}

				this.importLoading = true;
				var url = isSingle? '/student/getStuInfoByNumber' : '/classStudent/getClassStu',
					postData = isSingle? {stu_number: this.imptSearchText, class_cla_id: this.claId}
										:{class_cla_id: this.claId, cla_id: this.selectedClass};
				this.$http.post(url, postData).then(function(resp) {
		        	this.importLoading = false;
		            if (resp.data.status === 1) {
		            	var data = isSingle? [resp.data.data] : resp.data.data;
		            	if (data) {
		            		data.forEach(function(el) {
			            		el['checked'] = false;
			            	})
			                this.otherStus = data;
		            	} else {
		            		this.otherStus = [];
		            	}
		            	
		                if (this.otherStus.length == 0)
		                	this.notice = {type: 0, msg: "该班级暂时无可添加的学生"};
		            } else {
		            	this.notice = {type: 0, msg: resp.data.message};
		            }
			    }, function(resp) {
			        // error callback
			        this.importLoading = false;
			        this.notice = {type: 0, msg: resp.statusText};
			    })
			},
			beforeDel: function(isSingle, event, index) {
				if (!this.isSelectOne&&!isSingle) return;
				event.stopPropagation()

				$('#del-stus').modal('show');
				if (isSingle) {
					this.delInfo.content = this.students[index].stu_name;
					this.delInfo.delIndex = index;
				} else {
					var content = this.students.filter(function(el) {
						return el.checked;
					}).map(function(el) {
						if (el.checked) return el.stu_name;
					}).join(',');
					this.delInfo.content = content.length>18?content.substring(0, 19)+'...':content.substring(-1);
				}
				this.delInfo.title = '删除学生';
				this.delInfo.isSingle = isSingle;
			},
			delStus: function() {
				var delStusId = [];
				if (this.delInfo.isSingle) {
					delStusId[0] = this.students[this.delInfo.delIndex].stu_id;
				} else {
					delStusId = this.students.filter(function(el) {
						return el.checked;
					}).map(function(el) {
						if (el.checked) return el.stu_id;
					});
				}
				this.$http.post('/classStudent/removeStu',
		        	{cla_id: this.claId, stu_id: delStusId}).then(function(resp) {
		            if (resp.data.status === 1) {
		            	this.classInfo.cla_stu_num -= resp.data.data;
		                this.notice = {type: 1, msg: resp.data.message};
		                if (this.delInfo.isSingle) {
		                	this.students.splice(this.delInfo.delIndex, 1);
		                } else {
                        	this.delIfChecked(this.students);
                        }
		                $("#del-stus").modal("toggle");
		            } else {
		            	this.notice = {type: 0, msg: resp.data.message};
		            }
			    }, function(resp) {
			        // error callback
			        this.notice = {type: 0, msg: resp.statusText};
			    })
			},
			addStus: function() {
				var addStus = this.otherStus.map(function(el) {
					if (el.checked) return el.stu_id;
				});
				this.importLoading = true;
				this.$http.post('/classStudent/import',
		        	{cla_id: this.claId, stu_id: addStus}).then(function(resp) {
		        	this.importLoading = false;
		            if (resp.data.status === 1) {
		                this.notice = {type: 1, msg: resp.data.message};
		                this.delIfChecked(this.otherStus);
                        this.getStus();
                        this.classInfo.cla_stu_num = +this.classInfo.cla_stu_num + resp.data.data.success;
		                $("#add-stu").modal("toggle");
		            } else {
		            	this.notice = {type: 0, msg: resp.data.message};
		            }
			    }, function(resp) {
			        // error callback
			        this.importLoading = false;
			        this.notice = {type: 0, msg: resp.statusText};
			    })
			},
			allowApply: function() {
				this.ApplyLoading= true;
				var applyStus = this.applyStus.filter(function(el) {
					return el.checked;
				}).map(function(el) {
					return el.stu_id;
				})
				this.$http.post('/classStudent/allowJoin',
		        	{cla_id: this.claId, stu_id: applyStus}).then(function(resp) {
		        	this.ApplyLoading = false;
		            if (resp.data.status === 1) {
		                this.notice = {type: 1, msg: resp.data.message};
		                this.delIfChecked(this.applyStus);
		                this.applyNumber = this.applyStus.length;
                        this.getStus();
		                $("#apply-modal").modal("toggle");
		            } else {
		            	this.notice = {type: 0, msg: resp.data.message};
		            }
			    }, function(resp) {
			        // error callback
			        this.ApplyLoading = false;
			        this.notice = {type: 0, msg: resp.statusText};
			    })
			},
			delApply: function() {
				this.ApplyLoading = true;
				var applyStus = this.applyStus.filter(function(el) {
					return el.checked;
				}).map(function(el) {
					return el.stu_id;
				})
				this.$http.post('/classStudent/removeApply',
		        	{cla_id: this.claId, stu_id: applyStus}).then(function(resp) {
		        	this.ApplyLoading = false;
		            if (resp.data.status === 1) {
		                this.notice = {type: 1, msg: resp.data.message};
		                this.delIfChecked(this.applyStus);
		                this.applyNumber = this.applyStus.length;
                        this.getStus();
		                //$("#apply-modal").modal("toggle");
		            } else {
		            	this.notice = {type: 0, msg: resp.data.message};
		            }
			    }, function(resp) {
			        // error callback
			        this.ApplyLoading = false;
			        this.notice = {type: 0, msg: resp.statusText};
			    })
			},
			delIfChecked: function(arr) {
                for (var i = arr.length - 1; i >= 0; i--) {
					if (arr[i].checked)
						arr.splice(i, 1);
				}
			},
			toggle: function(arrName) {
				this[arrName].forEach(function(el) {
					el.checked = !el.checked;
				})
			}
		},
		watch: {
			searchText: function() {
				if (this.searchText === '') // 查询所有学生
					this.getStus(false);
			},
			classInfo: function() {
				this.getAllClasses();
			}
		}
	}
</script>

<style>
	#dropdown_os{
	    display: inline-block;
	    width: 60px;
	    height: 25px;
	    text-align: center;
	    border: 1px solid silver;
	    margin-right: 30px;
	}
	#dropdown_os a{
	    font-size: 15px;
	    color: black;
	}
	.table{
	    background-color: #fff;
	}
	.table .table-header{
	    background-color: #f5f5f5;
	}
	.modal-table {
		height: 300px;
		overflow: auto;
	}
	.stuInfo-table > tbody > tr > th, 
	.stuInfo-table > tbody > tr > td {
	    height: 50px;
	    text-align: center;
	    vertical-align: middle;
	}
	.modal-table th,
	.modal-table td {
		text-align: center;
	    vertical-align: middle;
	}
	.no_stu{
	    width: 100%;
	    height: 200px;
	    background-color: #e5e5e5;
	    text-align: center;
	    font-size: 20px;
	    padding-top: 50px;
	}
	#applyStuModel .modal-body,#addStuModel .modal-body #content{
	    height: 300px;
	    overflow-y: scroll;
	}
	/*返回班级管理的动画效果*/
	.navbar-header .left{
	    -webkit-transition: 1s ease-out all;
	    -moz-transition: 1s ease-out all;
	    -ms-transition: 1s ease-out all;
	    -o-transition: 1s ease-out all;
	    transition: 1s ease-out all;
	}
	.navbar-header .left:hover{
	    -webkit-transform: translate(-15px,0px);
	    -moz-transform: translate(-15px,0px);
	    -ms-transform: translate(-15px,0px);
	    -o-transform: translate(-15px,0px);
	    transform: translate(-15px,0px);
	}
	.stus-title {
		margin-bottom: 20px;
	}
	.stus-title .info {
		line-height: 40px;
		font-size: 16px;
	}
	.stuInfo-table {
		border: 1px solid #dce4ec;
	}
	.stuInfo-table tr td.edit-stu span[class$=remove],
	.stuInfo-table tr:hover td.edit-stu span[class$=horizontal]  {
		display: none;
	}
	.stuInfo-table tr:hover td.edit-stu span[class$=remove] {
		cursor: pointer;
		display: block;
	}
	.fade-transition {
		transition: all .8s ease;
		opacity: 1;
	}
	.fade-enter, .fade-leave {
		opacity: 0;
	}
</style>